using System.Diagnostics;
using System.Drawing;
using AutoClick.native;
using AutoClick.utils;

namespace AutoClick.capture.impl;

public class BitBltCapture : IGameCapture
{
    public Bitmap Capture(IntPtr hWnd)
    {
        var stopWatch = Stopwatch.StartNew();

        if (hWnd == IntPtr.Zero)
        {
            throw new ArgumentException("无效的窗口句柄", nameof(hWnd));
        }

        // 获取窗口的位置和大小
        if (!User32.GetWindowRect(hWnd, out Rect rect))
        {
            throw new Exception("无法获取窗口矩形");
        }

        // 创建一个 Bitmap 来保存截图
        var width = rect.Right - rect.Left;
        var height = rect.Bottom - rect.Top;
        var bitmap = new Bitmap(width, height);
        using (var g = Graphics.FromImage(bitmap))
        {
            var hdc = g.GetHdc();
            try
            {
                // 获取桌面设备上下文
                var desktopHdc = User32.GetDC(IntPtr.Zero);

                // 使用 BitBlt 复制图像
                if (!Gdi32.BitBlt(hdc, 0, 0, width, height, desktopHdc, rect.Left, rect.Top, 0x00CC0020))
                {
                    // Console.Error.WriteLine("spnapshot failed!");
                }

                // 释放桌面设备上下文
                User32.ReleaseDC(IntPtr.Zero, desktopHdc);
            }
            finally
            {
                g.ReleaseHdc(hdc);
            }
        }

        stopWatch.Stop();
        Console.WriteLine($"BITBLT Capture Time: {stopWatch.ElapsedMilliseconds}ms");

        return bitmap;
    }
}